"use strict";

const Service = require("egg").Service;

class RoleService extends Service {
  // 分页查询
  async page(params) {
    try {
      const { Op } = this.app.Sequelize;
      const offset = (Number(params.pi || 1) - 1) * Number(params.ps || 100);
      let queryCriteria = {
        deleFlag: false,
      };
      if (this.ctx.helper.isDef(params.status)) {
        queryCriteria = {
          ...queryCriteria,
          status: params.status,
        };
      }
      if (this.ctx.helper.isDef(params.keyword)) {
        queryCriteria = {
          ...queryCriteria,
          [Op.or]: [
            { roleName: { [Op.like]: `%${params.keyword}%` } },
            { roleKey: { [Op.like]: `%${params.keyword}%` } },
          ],
        };
      }
      const query = {
        limit: Number(params.ps || 100),
        offset,
        distinct: true, //这一句可以去重，它返回的 count 不会把你的 include 的数量算进去
        where: queryCriteria,
        attributes: { exclude: ["deleFlag"] },
      };
      const res = await this.ctx.model.Role.findAndCountAll(query);
      return this.ctx.helper.ormSuccess(res);
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }
  // 创建
  async create(params) {
    try {
      // 查询是否有重复的角色名称以及角色标识
      const { Op } = this.app.Sequelize;
      const query = {
        where: {
          deleFlag: false,
          [Op.or]: [
            {
              roleName: params.roleName,
            },
            {
              roleKey: params.roleKey,
            },
          ],
        },
      };
      const existData = await this.ctx.model.Role.findOne(query);
      if (existData) {
        if (existData.roleName === params.roleName) throw "角色名称已存在";
        if (existData.roleKey === params.roleKey) throw "角色标识已存在";
      }
      await this.ctx.model.Role.create(params);
      return this.ctx.helper.ormSuccess()
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }

  // 修改
  async update(id,params) {
    try {
      const { Op } = this.app.Sequelize;
      const updateObj = await this.ctx.model.Role.findByPk(id);
      if(!updateObj) throw '查询不到该角色';
      if(params.roleName) {
        // 查询是否有同名角色
        const existData = await this.ctx.model.Role.findOne({
          where: {
            deleFlag: false,
            roleName: params.roleName,
            id: {
              [Op.notIn]: [id]
            }
          }
        })
        if(existData) throw '角色名称已存在';
      }
      const res = await updateObj.update(params);
      return this.ctx.helper.ormSuccess(this.ctx.helper.deepCopy(res));
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }

  // 删除
  async del(params) {
    const transaction = await this.ctx.model.transaction();
    try {
      // 删除角色表
      const delObj = await this.ctx.model.Role.findByPk(params.id);
      if(!delObj) throw '查询不到该角色';
      await updateObj.update({deleFlag: true});
      // 删除角色菜单关联表
      await this.ctx.model.RoleMenu.destroy({
        where: {
          roleId: params.id
        }
      })
      // 删除用户角色关联表
      await this.ctx.model.UserRole.destroy({
        where: {
          roleId: params.id
        }
      })
      await transaction.commit();
      return this.ctx.helper.ormSuccess();
    } catch(err) {
      await transaction.rollback();
      return this.ctx.helper.ormError(err);
    }
  }
}

module.exports = RoleService;
